﻿using Avalonia;
using System;
using Avalonia.Controls;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog;
using NLog.Extensions.Logging;
using SchoolApp_Material.ViewModels;

namespace SchoolApp_Material;

sealed class Program
{
    // 静态日志实例，用于启动阶段的日志记录
    private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
    public static IServiceProvider ServiceProvider { get; private set; }
    public static Window? MainWindow { get; set; }
    
    // Initialization code. Don't use any Avalonia, third-party APIs or any
    // SynchronizationContext-reliant code before AppMain is called: things aren't initialized
    // yet and stuff might break.
    [STAThread]
    public static void Main(string[] args)
    {
        // 配置NLog
        LogManager.LoadConfiguration("NLog.config");
        _logger.Info("应用程序启动");
        // 初始化 ServiceCollection
        var services = new ServiceCollection();
        ConfigureServices(services);

        // 构建 ServiceProvider
        ServiceProvider = services.BuildServiceProvider();
        
        BuildAvaloniaApp()
            .StartWithClassicDesktopLifetime(args);
    }
    
    private static void ConfigureServices(IServiceCollection services)
    {
        // 配置日志
        services.AddLogging(logging =>
        {
            logging.ClearProviders();
            logging.AddNLog(); // 集成 NLog
        });
        //配置数据库
        Func<IServiceProvider, IFreeSql> fsqlFactory = r =>
        {
            IFreeSql fsql = new FreeSql.FreeSqlBuilder()
                .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=school.db")
                .UseAdoConnectionPool(true)
                .UseMonitorCommand(cmd => Console.WriteLine($"Sql：{cmd.CommandText}"))
                .UseAutoSyncStructure(true) //自动同步实体结构到数据库，只有CRUD时才会生成表
                .Build();
            return fsql;
        };
        services.AddSingleton<IFreeSql>(fsqlFactory);
        // 注册服务和 ViewModels
        services.AddTransient<LoginViewModel>();
        services.AddTransient<MainViewModel>();
        services.AddTransient<FormMgrViewModel>();
        services.AddTransient<FormEditViewModel>();
        services.AddTransient<TeacherMgrViewModel>();
        services.AddTransient<TeacherEditViewModel>();
        services.AddTransient<StudentMgrViewModel>();
        services.AddTransient<StudentEditViewModel>();
        // services.AddSingleton<IDataService, DataService>();
    }

    // Avalonia configuration, don't remove; also used by visual designer.
    public static AppBuilder BuildAvaloniaApp()
        => AppBuilder.Configure<App>()
            .UsePlatformDetect()
            .WithInterFont()
            .LogToTrace();
}